<template>
    <div>
        <div style="font-family: 幼圆;">
            <header id="nav-header">
                <div class="header-box">
                    <Row>
                        <Col :md="24" :sm="20" :xs="20">
                                <span class="nav-header-logo">
                                    <img src="../assets/logo.png"
                                         style="border-radius: 50%;margin-top: 2px;height: 70px" @click="this.$router.push(sHome)"/>
                                    <span style="font-size: 25px;margin:2%;font-weight: bolder;color: #2b85e4">blog</span>
                                </span>

                        </Col>

                        <Col :md="0" :sm="4" :xs="4">
                            <div class="tr">
                                <Icon @click="toggleMobileMenu" size="34" type="ios-menu" style="margin-top:8px"
                                      color="#000"/>
                            </div>
                        </Col>
                    </Row>
                </div>
            </header>
            <div id="main">
                <div>
                    <Row>
                        <Col :lg="24" :md="24" :sm="0" :xs="0">
                            <Menu mode="horizontal" @on-select="goPage" :active-name="currentRouterName">
                                <MenuItem name="SHome" to="sHome">
                                    <Icon type="ios-paper"/>
                                    博客
                                </MenuItem>
                                <MenuItem name="SType" to="sType">
                                    <Icon type="ios-bulb"/>
                                    分类
                                </MenuItem>
                                <MenuItem name="STag" to="sTag">
                                    <Icon type="md-pricetag"/>
                                    标签
                                </MenuItem>
                                <MenuItem name="SImage" to="sImage">
                                    <Icon type="md-images"/>
                                    图库
                                </MenuItem>
                                <MenuItem name="SAbout" to="sAbout">
                                    <Icon type="ios-ionitron"/>
                                    关于我
                                </MenuItem>
                                <MenuItem v-if="this.user.role === 'admin' ? true:false" name="6" to="admin">
                                    <Icon type="ios-ionitron"/>
                                    后台
                                </MenuItem>
                                <MenuItem name="7">
                                    <Input size="large" icon="ios-search" clearable placeholder="search..."
                                           v-model="Keyword" @on-enter="searchBlog()" @on-clear="searchClear()"/>
                                </MenuItem>
                                <div v-show="this.user.token == ''||this.user.token == null ? true:false"
                                     style="text-align: center;font-size: 20px">
                                    <Button @click="login" type="primary" icon="logo-reddit">微信登录
                                    </Button>

                                </div>
                                <Submenu name="8" v-show="this.user.token == ''||this.user.token == null ?false:true">
                                    <template slot="title">
                                        <Avatar :src="this.user.headimgurl"/>
                                        &nbsp;&nbsp;<span
                                            style="font-size: large">{{this.user.nickname,this.user.role}}</span>
                                    </template>
                                    <MenuGroup title="使用">
                                        <MenuItem name="3-3">
                                            <span @click="logout">退出登录</span>
                                        </MenuItem>
                                    </MenuGroup>
                                </Submenu>

                                <Modal v-model="loginModal"
                                       @on-cancel="closeLogin">
                                    <p style="text-align: center">
                                        <img width="200px" style="border-radius: 5px"
                                             :src="QrCodeURL"
                                             alt="">
                                    </p>
                                    <div slot="footer">
                                        <p style="text-align: center;font-size:20px">
                                            请使用微信扫一扫登录
                                        </p>
                                    </div>
                                </Modal>
                            </Menu>
                        </Col>
                        <Col :lg="0" :md="0" :sm="24" :xs="24">
                            <Drawer placement="left" :closable="false" v-model="showMobileMenu">
                                <Menu mode="vertical" @on-select="goPage" :active-name="currentRouterName">
                                    <MenuItem name="SHome" to="sHome">
                                        <Icon type="ios-paper"/>
                                        博客
                                    </MenuItem>
                                    <MenuItem name="SType" to="sType">
                                        <Icon type="ios-bulb"/>
                                        分类
                                    </MenuItem>
                                    <MenuItem name="STag" to="sTag">
                                        <Icon type="md-pricetag"/>
                                        标签
                                    </MenuItem>
                                    <MenuItem name="SImage" to="sImage">
                                        <Icon type="md-images"/>
                                        图库
                                    </MenuItem>
                                    <MenuItem name="SAbout" to="sAbout">
                                        <Icon type="ios-ionitron"/>
                                        关于我
                                    </MenuItem>
                                    <MenuItem v-if="this.user.role === 'admin' ? true:false" name="6" to="admin">
                                        <Icon type="ios-ionitron"/>
                                        后台
                                    </MenuItem>
                                    <template>

                                        <Input size="large" icon="ios-search" clearable placeholder="search..."
                                               v-model="Keyword" @on-enter="searchBlog()" @on-clear="searchClear()"/>
                                    </template>
                                    <br/>
                                    <br/>
                                    <div v-show="this.user.token == ''||this.user.token == null ? true:false"
                                         style="text-align: center;font-size: 20px">
                                        <Button @click="login" type="primary" icon="logo-reddit">微信登录
                                        </Button>

                                    </div>
                                    <Submenu name="8"
                                             v-show="this.user.token == ''||this.user.token == null ?false:true">
                                        <template slot="title">
                                            <Avatar :src="this.user.headimgurl"/>
                                            &nbsp;&nbsp;<span style="font-size: large">{{this.user.nickname}}</span>
                                        </template>
                                        <MenuGroup title="使用">
                                            <MenuItem name="3-3"><span @click="logout">退出登录</span></MenuItem>
                                        </MenuGroup>
                                    </Submenu>

                                </Menu>
                            </Drawer>
                        </Col>
                    </Row>
                </div>

                <div>
                    <!--                    内容显示窗口-->
                    <router-view :searchVal="searchVal"/>
                </div>

                <div id="footer">
                    <p>Wdhcr &copy; &nbsp;&nbsp;&nbsp;2020 </p>

                </div>
            </div>
        </div>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                flag: false,
                //控制扫码登录组件
                loginModal: false,
                currentRouterName: '',
                //导航栏的显示与隐藏
                showMobileMenu: false,
                //搜索博客的关键字
                Keyword: '',

                //用户登录的二维码地址
                QrCodeURL: '',
                //时间戳，作为webocket通信的唯一标识吗
                timestamp: '',

                //扫码登录后的用户信息
                user: {
                    headimgurl: '',
                    nickname: '',
                    token: '',
                    role: '',

                },
                //将搜索的内容传递给博客列表组件的中间值
                searchVal: {},


            }
        },
        created() {
            //获取当前地址栏路径，选中菜单
            this.currentRouterName = this.$route.name

            //打开网页时获取登录二维码
            this.getQrcodeUrl();
            if (window.sessionStorage.getItem("user") != null) {
                const redata = JSON.parse(window.sessionStorage.getItem("user"));
                this.user = redata;
                this.user.role = window.sessionStorage.getItem("role");

            }


        },
        //用来监测Vue实例上的数据变动。
        watch: {
            //检测路由的变化，
            '$route'(newRoute) {
                this.currentRouterName = newRoute.name
            },
        },
        mounted() {
            //处理当屏幕小于768时隐藏横向导航栏
            window.onresize = () => {
                if (window.innerWidth >= 768) {
                    this.showMobileMenu = false
                }
            }
        },
        methods: {
            //当处于手机端时切换导航栏的显示与隐藏
            goPage() {
                this.showMobileMenu = false
            },
            //控制手机端时的导航栏的显示与隐藏
            toggleMobileMenu() {
                this.showMobileMenu = !this.showMobileMenu
            },

            //点击登录按钮触发的方法
            login() {
                this.loginModal = !this.loginModal;

                //当点击登录按钮时时初始化websocket
                this.initWebSocket();
            },
            logout() {
                window.sessionStorage.removeItem("user");
                window.location.reload();
            },

            //当关闭了登录窗口时，触发，关闭websocket长连接
            closeLogin() {
                this.close();
            },
            //获取微信登录二维码的方法
            async getQrcodeUrl() {
                this.timestamp = new Date().getTime() + "";
                this.timestamp = this.timestamp.substring(0, this.timestamp.length - 3);
                console.log(this.timestamp);

                const {data: result} = await this.$http.get('getTicket?sceneId=' + this.timestamp)
                this.QrCodeURL = this.$getcodeurl + result;


            },
            //初始化websocket方法，当点击登录按钮时，建立连接
            initWebSocket() {
                let websocket = null;
                if ('WebSocket' in window) {
                    websocket = new WebSocket("ws://" + this.$wsUrl + "/websocket/" + this.timestamp);
                } else {
                    alert('当前浏览器  Not support websocket');
                }
                websocket.onopen = this.open;
                websocket.onmessage = this.getMessage;
                websocket.onclose = this.close;
                websocket.onerror = this.error;
            },
            open: function () {
                console.log("socket连接成功")
            },
            error: function () {
                console.log("连接错误")
            },
            getMessage: function (msg) {
                if (msg != "" || msg != null) {
                    window.sessionStorage.setItem("user", msg.data);
                    const redata = JSON.parse(msg.data);
                    this.user = redata;
                    //当获取到信息后隐藏登录框
                    this.loginModal = !this.loginModal;
                    this.close();
                    this.getUserRole();

                }

            },

            close: function () {
                console.log("socket已经关闭")

            },
            //获取用户角色权限
            async getUserRole() {
                const {data: result} = await this.$http.post("getRole");
                if (result.code === 200) {
                    window.sessionStorage.setItem("role", result.data)
                    window.setTimeout(function () {
                        window.sessionStorage.removeItem("role");
                        window.sessionStorage.removeItem("user");
                        window.location.reload();
                    }, 7200000); //有效时间两个小时
                    this.$set(this.user, 'role', result.data)
                    this.$forceUpdate();
                    this.$Message.success(result.message);
                } else {
                    this.$Message.error(result.message);
                }

            },
            //搜索博客的方法
            async searchBlog() {
                const {data: result} = await this.$http.post("searchShowBlog", this.Keyword)
                if (result.code === 200) {
                    if (this.showMobileMenu) {
                        this.showMobileMenu = !this.showMobileMenu
                    }
                    this.searchVal = result;
                }
            },
            //搜索框清除按钮
            searchClear() {
                if (this.showMobileMenu) {
                    this.showMobileMenu = !this.showMobileMenu
                }
                this.searchVal = undefined;
            },
        }
    }
</script>
<style lang="less">
    #nav-header {
        width: 100%;
        height: 50px;
        padding: 0 40px;
        box-sizing: border-box;
        z-index: 1000;
        position: fixed;
        top: 0;
        background-color: #fff;
        box-shadow: 0 1px 3px rgba(26, 26, 26, .1);
        font-size: 14px;

        .header-box {
            max-width: 1400px;
            margin: 0 auto;
        }

        .nav-header-logo {
            img {
                height: 46px;
                vertical-align: middle;
            }

            span {
                font-family: 幼圆;
                font-size: 16px;
                font-weight: bolder;
            }
        }
    }

    #main {
        max-width: 1400px;
        margin: 60px auto 20px auto;
    }


    #footer {
        text-align: center;
        padding: 10px;
    }
</style>

